#include <iostream>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>

int main() {
    // 1. 创建套接字
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) { perror("socket"); return 1; }

    // 2. 绑定 IP 和端口
    sockaddr_in addr{};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY; // 本机任意 IP
    addr.sin_port = htons(12345);      // 端口 12345
    if (bind(server_fd, (sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind"); return 1;
    }

    // 3. 监听
    listen(server_fd, 5);
    std::cout << "服务端启动，等待客户端连接..." << std::endl;

    // 4. 接受连接
    sockaddr_in client_addr{};
    socklen_t len = sizeof(client_addr);
    int client_fd = accept(server_fd, (sockaddr*)&client_addr, &len);
    if (client_fd < 0) { perror("accept"); return 1; }
    std::cout << "客户端已连接！" << std::endl;

    // 5. 收发数据
    char buffer[1024];
    int n = read(client_fd, buffer, sizeof(buffer)-1);
    if (n > 0) {
        buffer[n] = '\0';
        std::cout << "收到客户端消息: " << buffer << std::endl;
        std::string reply = "Hello from server!";
        write(client_fd, reply.c_str(), reply.size());
    }

    // 6. 关闭连接
    close(client_fd);
    close(server_fd);
    return 0;
}
